import { Session, Local } from './storage';
import { loginByToken } from '/@/api/login';
import { getUserInfo } from '/@/api/common';

// 存储token
// export const setToken = (function () {
// 	let hasExecuted = false;

// 	return function () {
// 		if (hasExecuted) return;
// 		hasExecuted = true;

// 		const url = window.location.href;
// 		if (!url.includes('token')) {
// 			return;
// 		}
// 		const params = new URLSearchParams(url.split('?')[1]);
// 		const preToken = Session.getToken();
// 		const token = params.get('token');
// 		if (preToken !== token) {
// 			Session.set('token', token);
// 			getUserInfo(token).then((res: any) => {
// 				if (res.ok) {
// 					Local.set('userInfos', res.data);
// 				}
// 			});
// 		}
// 	};
// })();
// 免登
export const setToken = (function () {
	let hasExecuted = false;
  
	return async function () {
	  if (hasExecuted) return Promise.resolve();
	  hasExecuted = true;
  
	  const url = window.location.href;
	  if (!url.includes('token')) {
		return Promise.resolve();
	  }
  
	  const params = new URLSearchParams(url.split('?')[1]);
	  const token = params.get('token');
	  try {
		const res = await loginByToken({ ticket: token });
		if (res?.ok) {
		  const preToken = Session.getToken();
		  if (preToken !== res?.data) {
			Session.set('token', res?.data);
		  }
		} else {
		  showFailToast(res?.msg || '登录失败');
		}
	  } catch (error) {
		showFailToast(error || '登录失败')
	  }
	};
})();

// 样式转换(用于行内样式)
export const pxToRem = (px: any) => {
	let newPx: number | string = px;
	let newPxNumber: number = 0;
	if (typeof px === 'string') {
		if (/%/gi.test(px)) {
			return px;
		}
		newPxNumber = parseFloat(px.replace('px', ''));
	}

	if (isNaN(newPxNumber)) return newPx;

	const baseFontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
	const remValue = (px / baseFontSize).toFixed(6) + 'rem';
	return remValue;
};
